<template>
  <!-- 计划维修明细表单弹窗 -->
  <div>
    <el-dialog
      :close-on-click-modal="false"
      v-model="visibleDialog"
      :title="props.title"
      :width="!props.isReadonly ? '850px' : '850px'"
      draggable
      @close="closeDialog"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :inline="true"
        :rules="rules"
        v-show="!props.isReadonly"
        label-width="120"
      >
        <div>
          <el-row>
            <el-col :span="12">
              <el-form-item label="设备" prop="assetName" style="width: 100%">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.assetName"
                  placeholder="请选择设备"
                  @focus="openSelectDialog()"
                  clearable
                />
                <span v-else>{{ formData.assetName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="位置"
                prop="locationName"
                style="width: 100%"
              >
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.locationName"
                  placeholder="请输入位置"
                  disabled
                  clearable
                />
                <span v-else>{{ formData.locationName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="设备种类"
                prop="assetTypeName"
                style="width: 100%"
              >
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.assetTypeName"
                  placeholder="请输入设备种类"
                  disabled
                  clearable
                />
                <span v-else>{{ formData.assetTypeName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="品牌型号"
                prop="getAssetModelNo"
                style="width: 100%"
              >
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.getAssetModelNo"
                  placeholder="请输入品牌型号"
                  disabled
                  clearable
                />
                <span v-else>{{ formData.getAssetModelNo }}</span>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item
                label="维修类型"
                prop="repairType"
                style="width: 100%"
              >
                <el-select
                  v-model="formData.repairType"
                  placeholder="请选择维修类型"
                  style="width: 100%"
                  clearable
                >
                  <el-option
                    v-for="item in dictionaryStore.filterDictList(
                      'PlanRepairType'
                    )"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item
                label="维修班组"
                prop="executeTeamId"
                style="width: 100%"
              >
                <el-select
                  v-model="formData.executeTeamId"
                  placeholder="请选择维修班组"
                  style="width: 100%"
                  clearable
                  @change="changeTeam"
                >
                  <el-option
                    v-for="item in executeTeamList"
                    :key="item.id"
                    :label="item.teamName"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item
                label="维修人员"
                prop="executeUserIds"
                style="width: 100%"
              >
                <el-select
                  v-model="formData.executeUserIds"
                  placeholder="请选择维修人员"
                  :multiple="true"
                  style="width: 100%"
                  clearable
                  @change="changeExecuteUser"
                >
                  <el-option
                    v-for="item in executeTeamMemberList"
                    :key="item.memberId"
                    :label="item.memberName"
                    :value="item.memberId"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="计划开始时间"
                prop="planStartTime"
                style="width: 100%"
              >
                <!-- <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.planStartTime"
                  placeholder="请输入计划开始时间"
                  clearable
                /> -->
                <el-date-picker
                  style="width: 500px"
                  v-if="!props.isReadonly"
                  v-model="formData.planStartTime"
                  type="date"
                  placeholder="请输入计划开始时间"
                  format="YYYY/MM/DD"
                  value-format="YYYY-MM-DD"
                />
                <span v-else>{{ formData.planStartTime }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="计划时间(小时)"
                prop="planHour"
                style="width: 100%"
              >
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.planHour"
                  placeholder="请输入计划时间(小时)"
                  clearable
                />
                <span v-else>{{ formData.planHour }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item
                label="计划维修内容"
                prop="remarks"
                style="width: 100%"
              >
                <el-input
                  maxlength="255"
                  show-word-limit
                  type="textarea"
                  v-if="!props.isReadonly"
                  :autosize="{ minRows: 2, maxRows: 2 }"
                  v-model="formData.remarks"
                  placeholder="请输入计划维修内容"
                  clearable
                />
                <span v-else>{{ formData.remarks }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item
                label="维修要求"
                prop="repairRequirement"
                style="width: 100%"
              >
                <el-input
                  maxlength="255"
                  show-word-limit
                  type="textarea"
                  v-if="!props.isReadonly"
                  :autosize="{ minRows: 2, maxRows: 2 }"
                  v-model="formData.repairRequirement"
                  placeholder="请输入维修要求"
                  clearable
                />
                <span v-else>{{ formData.repairRequirement }}</span>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <div
          style="
            display: flex;
            justify-content: space-between;
            align-items: center;
          "
          v-if="!props.isReadonly"
        >
          <h4 class="mb-[20px] mt-[20px]">备件清单</h4>
          <el-button
            type="success"
            plain
            @click="handleAddSparepart"
            v-if="!props.isReadonly"
          >
            <i-ep-plus />
            新增
          </el-button>
        </div>
        <div>
          <el-table
            :data="formData.details"
            style="width: 100%"
            :key="Math.random"
            max-height="240px"
            overflow-y="auto"
            border
            class="formTable2"
          >
            <el-table-column
              type="index"
              label="序号"
              align="center"
              width="100"
            />
            <el-table-column label="备件" props="spareNmae" min-width="150">
              <template #default="{ $index, row }">
                <span
                  >{{ row.spareNmae }}{{ row.spareNmae ? "-" : ""
                  }}{{ row.spareCode }}</span
                >
              </template>
            </el-table-column>
            <el-table-column
              label="备件类型"
              props="spareType"
              min-width="150"
              align="center"
            >
              <template #default="scope">
                {{ useDictionary("SpareType", scope.row.spareType) }}
              </template>
            </el-table-column>
            <el-table-column
              label="备件数量"
              props="sparePartNumber"
              min-width="150"
              align="center"
            >
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'details.' + $index + '.sparePartNumber'"
                  :rules="rules.sonsparePartNumber"
                  label-width="0"
                >
                  <el-input
                    style="width: 130px"
                    v-if="!props.isReadonly"
                    v-model="row.sparePartNumber"
                    placeholder="请输入备件数量"
                    clearable
                  />
                  <span v-else>{{ row.sparePartNumber }}</span>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              label="备件单位"
              props="spareUnit"
              min-width="150"
              align="center"
            >
              <template #default="{ $index, row }">
                <span>{{ row.spareUnit }}</span>
              </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              align="center"
              label="操作"
              width="100"
              v-if="!props.isReadonly"
            >
              <template #default="scope">
                <el-button
                  type="danger"
                  link
                  @click.stop="handleDelete(scope.$index)"
                >
                  <i-ep-delete />
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>
      <el-descriptions
        v-show="props.isReadonly"
        class="margin-top"
        title=""
        :column="2"
        size="large"
        border
      >
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">设备</div>
          </template>
          {{ formData.assetName }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">位置</div>
          </template>

          <div style="width: 100%; word-break: break-all">
            {{ formData.locationName }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">设备种类</div>
          </template>
          {{ formData.assetTypeName }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">品牌型号</div>
          </template>
          {{ formData.getAssetModelNo }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">维修类型</div>
          </template>
          {{ useDictionary("PlanRepairType", formData.repairType) }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">维修班组</div>
          </template>
          {{ formData.executeTeamName }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">维修人员</div>
          </template>
          {{ formData.executeUsers.map((item) => item.personName).join(",") }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">计划开始时间</div>
          </template>
          {{
            formData.planStartTime
              ? dayjs(formData.planStartTime).format("YYYY-MM-DD")
              : ""
          }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">计划时间(小时)</div>
          </template>
          {{ formData.planHour }}
        </el-descriptions-item>

        <el-descriptions-item :span="2">
          <template #label>
            <div class="cell-item">计划维修内容</div>
          </template>
          <div style="width: 100%; word-break: break-all">
            {{ formData.remarks || "暂无备注" }}
          </div>
        </el-descriptions-item>

        <el-descriptions-item :span="2">
          <template #label>
            <div class="cell-item">维修要求</div>
          </template>
          <div style="width: 100%; word-break: break-all">
            {{ formData.repairRequirement }}
          </div>
        </el-descriptions-item>
      </el-descriptions>
      <el-table
        v-show="props.isReadonly"
        :data="formData.details"
        style="width: 100%; margin-top: 20px"
        :key="Math.random"
        max-height="240px"
        overflow-y="auto"
        border
      >
        <el-table-column type="index" label="序号" align="center" width="100" />
        <el-table-column label="备件" props="spareNmae" min-width="150">
          <template #default="{ $index, row }">
            <span
              >{{ row.spareNmae }}{{ row.spareNmae ? "-" : ""
              }}{{ row.spareCode }}</span
            >
          </template>
        </el-table-column>
        <el-table-column
          label="备件类型"
          props="spareType"
          min-width="150"
          align="center"
        >
          <template #default="scope">
            {{ useDictionary("SpareType", scope.row.spareType) }}
          </template>
        </el-table-column>
        <el-table-column
          label="备件数量"
          props="sparePartNumber"
          min-width="150"
          align="center"
        >
          <template #default="{ $index, row }">
            <span>{{ row.sparePartNumber }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="备件单位"
          props="spareUnit"
          min-width="150"
          align="center"
        >
          <template #default="{ $index, row }">
            <span>{{ row.spareUnit }}</span>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="!props.isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定
          </el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <common-sparepart-select
      :visible="selectSparepartDialog.visible"
      :breakList="SparepartList"
      @change-visible="changeSparepartVisible"
    />
    <devicechangestatus-select
      :visible="selectDialog.visible"
      @change-visible="changeVisible"
    />
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
import { useTable, useDictionary } from "@/utils/useTable";
const dictionaryStore = useDictStoreHook();
import { useRouter, useRoute } from "vue-router";
import dayjs from "dayjs";
const router = useRouter();
const route = useRoute();
defineOptions({
  name: "COMMONREPAIRPLANDETAILADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  assetKind: {
    type: Number,
    default: null,
  },
});

/** 弹窗显示 **/
const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

/** formData定义表单数据 */
const formRef = ref(ElForm);
let formData = reactive({
  id: "",
  version: "",
  planId: route.query.id,
  propertyId: "",
  propertyCode: "",
  assetName: "",
  assetCode: "",
  planStartTime: "",
  planHour: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: "",
  assetKind: props.assetKind,
  deleted: "",
  locationName: "",
  assetTypeId: "",
  assetTypeName: "",
  assetTypeCode: "",
  assetBrandName: "",
  getAssetModelNo: "",
  repairType: "",
  executeTeamId: "",
  executeTeamName: "",
  executeUserIds: [],
  executeUsers: [],
  repairRequirement: "",
  details: [
    // {
    //   id: "",
    //   planDetailId: "",
    //   sparePartId: "",
    //   sparePartNumber: "",
    //   version: "",
    //   remarks: "",
    //   createTime: "",
    //   createdUserId: "",
    //   createdUserName: "",
    //   lastUpdateTime: "",
    //   lastUpdatedUserId: "",
    //   lastUpdatedUserName: "",
    //   enabled: "",
    //   deleted: "",
    // },
  ],
});

/** rules规则 */
const rules = reactive({
  version: [],
  assetName: [{ required: true, message: "请选择设备", trigger: "change" }],
  repairType: [
    { required: true, message: "请选择维修类型", trigger: "change" },
  ],
  executeTeamId: [
    { required: true, message: "请选择维修班组", trigger: "change" },
  ],
  executeUserIds: [
    { required: true, message: "请选择维修人员", trigger: "change" },
  ],
  repairRequirement: [],

  planHour: [
    {
      required: true,
      message: "请输入计划时间",
      trigger: "blur",
      pattern: /^([1-9]{1,2}|100)$/,
    },
  ],
  remarks: [
    {
      required: true,
      message: "请输入计划维修内容",
      trigger: "blur",
    },
    { min: 1, max: 255, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  planStartTime: [
    {
      required: true,
      message: "请选择计划开始时间",
      trigger: "change",
    },
  ],

  sonplanDetailId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  sonsparePartId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  sonsparePartNumber: [
    {
      required: true,
      message: "请输入备件数量",
      trigger: "blur",
      pattern: /^([0-9]{1,4}|100)$/,
    },
  ],
});
const isValidated = ref(false);
/** 删除行 */
const handleDelete = (index: any) => {
  formData.details.splice(index, 1);
  isValidated.value && formRef.value.validate(() => {});
};

const details = {
  id: "",
  planDetailId: route.query.id,
  sparePartId: "",
  sparePartNumber: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: "",
  deleted: "",
};

/** 添加行 */
const handleAddSparepart = () => {
  selectSparepartDialog.value.visible = true;

  if (formData.details.length > 0) {
    getSparepartList();
  }
};

/** 编辑时赋值 */
watch(
  () => props.data,
  async (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      await changeTeam(props.data?.executeTeamId);
      Object.assign(formData, props.data);
      if (formData.id) {
        getdetails();
        formData.getAssetModelNo = `  ${formData.getAssetModelNo}  ${
          formData.getAssetModelNo ? "-" : ""
        }${formData.assetBrandName}`;

        formData.assetTypeName = `${formData.assetTypeCode} ${
          formData.assetTypeCode ? "-" : ""
        }${formData.assetTypeName}`;

        formData.assetName = ` ${formData.assetCode} ${
          formData.assetCode ? "-" : ""
        }${formData.assetName}`;

        // getTypeList(formData.propertyId);
      } else {
        formData.assetKind = props.assetKind;
      }
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.details = [];
  formData.id = "";
  formData.version = "";
  formData.planId = route.query.id;
  formData.propertyId = "";
  formData.assetName = "";
  formData.assetCode = "";

  formData.planStartTime = "";
  formData.planHour = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = "";
  formData.deleted = "";
  formData.assetKind = props.assetKind;
  formData.locationName = "";
  formData.assetTypeId = "";
  formData.assetTypeName = "";
  formData.assetTypeCode = "";

  formData.assetBrandName = "";
  formData.getAssetModelNo = "";
  formData.repairType = "";
  formData.executeTeamId = "";
  formData.executeTeamName = "";
  formData.executeUserIds = [];
  formData.executeUsers = [];
  formData.repairRequirement = "";
  SparepartList.value = [];
}

const loading = ref(false);

/** 计划维修明细保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      // if (formData.details.length == 0) {
      //   ElMessage.error("请选择至少一件备件");
      //   return;
      // }
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      console.log("formData", toRaw(formData));
      await request({
        url: "/eam/eamrepairplandetail/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
      isValidated.value = false;
    } else {
      isValidated.value = true;
    }
  });
}

async function getdetails() {
  let sondetails = await request({
    url: "/eam/eamrepairplandetail/getDetails",
    method: "post",
    data: formData,
  }).finally(() => {
    loading.value = false;
  });

  formData.details = sondetails.data;
  console.log(formData.details);
}

// 资产位置
//资产位置显隐
const selectSparepartDialog: any = ref({
  visible: false,
});
const changeSparepartVisible = (val: boolean, data: any) => {
  if (data) {
    console.log(11, data);

    formData.details = [];
    data.forEach((item) => {
      formData.details.push({
        planDetailId: route.query.id,
        sparePartId: item.id,
        spareType: item.spareType,
        spareUnit: item.spareUnit,
        spareCode: item.spareCode,
        spareNmae: item.spareNmae,
      });
    });
  }
  selectSparepartDialog.value.visible = val;
};

// 新增完返回的数据用于显示选择器
const SparepartList = ref([]);
const getSparepartList = () => {
  SparepartList.value = [];
  formData.details.forEach((item) => {
    if (item.sparePartId) {
      SparepartList.value.push({
        id: item.sparePartId,
        spareType: item.spareType,
        spareCode: item.spareCode,
        spareNmae: item.spareNmae,
        spareUnit: item.spareUnit,
      });
    }
  });
};

//  点击设备

function openSelectDialog() {
  changeVisible(true, null);
}
//设备显隐
const selectDialog = ref({
  visible: false,
});
const changeVisible = (val: boolean, data: any) => {
  if (data) {
    formData.assetId = data.id;
    formData.assetCode = data.assetCode;
    formData.assetName = `${data.assetName}${data.assetName ? "-" : ""}${
      data.assetTypeCode
    }`;
    formData.locationName = data.locationName;
    formData.assetTypeId = data.assetTypeId;
    formData.assetTypeName = ` ${data.assetTypeCode}${
      data.assetTypeCode ? "-" : ""
    }${data.assetTypeName}`;

    formData.assetBrandName = data.assetBrandName;
    formData.getAssetModelNo = ` ${data.assetModelNo}${
      data.assetModelNo ? "-" : ""
    }${data.assetBrandName}`;
  }
  selectDialog.value.visible = val;
};

const executeTeamList = ref([]);

const getExecuteTeamList = async () => {
  const { data } = await request({
    url: "/eam/eamTeam/getList",
    method: "post",
    data: {},
  });
  executeTeamList.value = data;
};

const executeTeamMemberList = ref([]);

const changeTeam = async (teamId) => {
  if (teamId) {
    formData.executeTeamName = executeTeamList.value.find(
      (item) => teamId === item.id
    )?.teamName;
    const { data } = await request({
      url: "/eam/eamteammember/getList",
      method: "post",
      data: { teamId },
    });
    executeTeamMemberList.value = data;
  } else {
    formData.executeTeamName;
    executeTeamMemberList.value = [];
  }
  formData.executeUserIds = [];
};

const changeExecuteUser = () => {
  formData.executeUsers = executeTeamMemberList.value
    .filter((item) => formData.executeUserIds.includes(item.memberId))
    .map(
      ({
        memberId: personId,
        memberEmpNo: personEmpNo,
        memberName: personName,
        organizationId,
      }) => ({
        personId,
        personEmpNo,
        personName,
        organizationId,
      })
    );
};
onMounted(() => {
  getExecuteTeamList();
});
</script>

<style lang="scss" scoped>
.formTable2 {
  :deep(.el-form-item) {
    margin: 0 0 13px 0 !important;
    width: 100%;
  }
}

:deep(.formTable2 .el-form-item) {
  padding: 11px 0 0 0 !important;
}
:deep(.formTable2 .el-form-item__error) {
  font-size: 11px !important;
}

:deep(.formTable2) {
  // .cell.el-tooltip {
  //   padding: 0 15px;
  // }
  // .el-table__body td.el-table__cell {
  //   padding: 20;
  // }
  // .cell.el-tooltip {
  //   padding: 5px;
  // }
  .el-table__body td.el-table__cell {
    // padding: 5px !important;
    padding: 0 !important;
  }
}

:deep(.el-descriptions__label.el-descriptions__cell.is-bordered-label) {
  width: 160px;
}
:deep(.el-descriptions__content.el-descriptions__cell.is-bordered-content) {
  min-width: 180px;
}
</style>
